<template id="userTemplate">
  <div style="width: 100%;margin-top: 0px;">
    <div class="mt-4" style="margin-top: 20px;margin-bottom: 20px;">

      <el-button style="margin-left: -4.3%" type="danger" @click="deleteChecked(tableChecked)">批量删除</el-button>

      <el-button type="primary" plain style="margin-left: 20px" @click="addUsers">添加用户</el-button>
      <el-input
          v-model="userName"
          placeholder="请输入用户名称"
          @clear="getUserList"
          class="input-with-select"
          clearable
          style="width: 15%;margin-left: 10.5%"
      >
      </el-input>
      <el-button type="primary" id="sele" style="margin-left: 10px;" @click="getUserList()">
        <i class="el-icon-zoom-in"></i>搜索
      </el-button>
    </div>
    <el-table :data="userList" @selection-change="handleSelectionChange" border style="width: 100%;text-align: center;font-weight: bold;margin-top: 40px;border-left: none">
      <el-table-column type="selection" width="55" />
      <el-table-column label="用户编号" prop="userId" />
      <el-table-column label="用户名" prop="userName" />
      <el-table-column label="用户密码" prop="userPwd" />
      <el-table-column label="角色" prop="userRoleId" >
        <template #default="scope">
          {{
            scope.row.userRoleId== 1
                ? "店长"
                : scope.row.userRoleId== 2
                ? "员工":""
          }}</template>
      </el-table-column>
      <el-table-column label="地址" prop="userAddress" />
      <el-table-column label="手机号" prop="userPhone" />

      <el-table-column label="操作"  >
        <template slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.userId)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button type="primary" icon="el-icon-delete" size="mini" @click="deleteUsersById(scope.row.userId)"
          ></el-button>

        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="demo-pagination-block">
      <el-pagination
          :current-page="limit.page"
          :page-sizes="[1,2,3,5,10]"
          :page-size="limit"
          :small="small"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>





    <el-dialog title="新增用户" :visible.sync="addDialogVisible" width="30%" top="13%"  center>
      <el-form
          ref="addFormRef"
          :model="addUser"
          status-icon
          label-width="100px"
          class="demo-ruleForm"
          style="margin-left: 15%;width:300px"
      >
        <el-form-item label="用户名字:" prop="userName">
          <el-input v-model="addUser.userName" />
        </el-form-item>
        <el-form-item label="用户密码:" prop="userPwd">
          <el-input v-model="addUser.userPwd" />
        </el-form-item>
        <el-form-item label="用户角色:" prop="userRoleId">
          <el-select v-model="addUser.userRoleId" placeholder="职位">
            <el-option label="店长" value="1"></el-option>
            <el-option label="员工" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号:" prop="userPhone">
          <el-input v-model="addUser.userPhone" />
        </el-form-item>
        <el-form-item label="地址:" prop="userAddress">
          <el-input v-model="addUser.userAddress" />
        </el-form-item>

        <el-form-item style="margin-top: 30px">
          <el-button type="primary" @click="inserts('add')">确定</el-button
          >
          <el-button @click="">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>



    <!--修改的窗口-->
    <el-dialog title="修改用户信息" :visible.sync="editFormVisible" width="30%" top="13%"  center>
      <!--有多个form表单 怎么区分 ref="名字"  获取的形式 this.$refs['名字']-->
      <el-form ref="editForm" :rules="addFormRules" :model="editForm" status-icon
               label-width="100px"
               class="demo-ruleForm"
               style="margin-left: 15%;width:300px">
        <el-form-item label="用户编号" :label-width="formLabelWidth">
          <el-input v-model="editForm.userId" :disabled="true" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="userName">
          <el-input v-model="editForm.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth">
          <el-input v-model="editForm.userPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-select v-model="editForm.userRoleId" placeholder="请选择" autocomplete="off">
            <el-option label="店长" value="1"></el-option>
            <el-option label="员工" value="2"></el-option>
          </el-select>

          <!--<el-input v-model="editForm.userRoleName" autocomplete="off"></el-input>-->

        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="editForm.userPhone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="editForm.userAddress" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit('editForm')">确 定</el-button>
      </div>
    </el-dialog>









  </div>
</template>

<script>
import calms from "@/netWork/request"

export default {
  name: "selectUser",
  data() {
    return {
      //选中id的集合
      tableChecked:[], //存放删除的数据
      multipleSelection:[],//多选的数据
      delVisible:false,//删除提示框
      //新增的数据集合
      addUser: {
        userName: "", userPwd: "",
        userRoleId: "", userPhone: "", userAddress: ""
      },
      editFormVisible: false,//修改窗口的显示隐藏开关
      editForm: { //修改对象
        userId: '',
        userName: '',
        userPwd: '',
        userRoleName: '',
        userPhone: '',
        userAddress: ''
      },
      //修改的数据集合
      editUser: {
        brandName: ""
      },
      addDialogVisible: false,//新增弹框
      dialogVisible: false,//编辑弹框

      // 表格数据
      userList: [],
      userName: "",
      //大小
      small: false,
      //分页背景颜色
      background: true,
      total: 0,
      //第几页 默认第一页
      page: 1,
      //一页显示多少 默认5
      limit: 5
    }
  },
  // 界面初始化就要调用
  created() {
    this.getUserList()
  },

  methods: {

    handleSizeChange(val) {
      this.limit = val;  // 修改显示数
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.page = val;  // 更新当前的页
      this.getUserList()
    },


    //根据Id批量删除
    deleteChecked(val){
      //提示语
      this.$confirm('确定删除用户？', '提示', {
        confirmButtonText: '确定',
        cancleButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const length = this.multipleSelection.length;
        for (let i = 0; i < length; i++) {
          this.tableChecked.push(this.multipleSelection[i].userId)
        }
        let data= new Array(this.tableChecked)
        let userIds="";
        data.forEach((id)=>{
              userIds+=id+","
            }
        )
        calms({
          url: '/deleteDuoUsers',
          method: "delete",
          contentType: "application/json",
          params: {userId:userIds},
        }, res => {
          console.log("删除信息：" + res.data);
          if (res.data >=1) {
            this.getUserList();
            this.$message.success('删除成功')
            this.getMenuList();
            location.reload()
          } else {
            this.$message.error('删除失败')
          }
        }, err => {
          console.log(err);
        },8100)
      })
    },



    // 获取表格数据
    async getUserList() {
      calms({
        url: '/selectLikeUsers',
        method: "get",
        contentType: "application/json",
        params: {
          userName: this.userName,
          page: this.page,
          limit: this.limit
        }
      }, res => {
        //console.log("集合大小" + res.data);
        this.total = res.data.count;
        this.userList = res.data.data;
        console.log(this.userList = res.data.data);
      }, err => {
        // eslint-disable-next-line no-console
        console.log(err);
      },8100)

    },
    deleteUsersById(userId){
      console.log("选中的ID是：" + userId);

      this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        calms({
          method:'delete',
          url: 'deleteDuoUsers?userId=' + userId,
        },res=>{
          this.getUserList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        },error=>{
          //提示信息框
          console.log(error);
        },8100)

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    //监听获得选中行数据
    handleSelectionChange(val){
      this.multipleSelection =val
    },

    userEdit(row) {
      this.dialogVisible = true;
      this.editUser = row;
    },
    addUsers() {
      this.addDialogVisible = true;
    },
    //增加用户表格
    inserts() {
      this.$refs.addFormRef.validate(valid => {
        if (valid) {//验证成功，则发请求到axios
          // async声明发放为异步方法 await等待异步操作执行完毕
          if (!valid) return
          calms({
            url: '/addUsers',
            method: "post",
            contentType: "application/json",
            params: this.addUser
          }, res => {
            // eslint-disable-next-line no-console
            //console.log(res.data);
            if (res.data >=1) {
              this.getUserList();
              this.$message.success("增加成功")

            }
            this.menuList = res.data;
          }, err => {
            // eslint-disable-next-line no-console
            console.log(err);
          },8100)
          //3)关闭窗口
          this.addDialogVisible=false;
        }
      })
    },
    //修改弹窗
    showEditDialog(userId){
      this.$request({
        method:'GET',
        url: 'selectIdUser?userId=' + userId,

      },res=>{
        this.editForm = res.data;
        console.log(this.editForm.userId);
      },error=>{
        //提示信息框
        console.log(error);
      },8100)
      console.log("虽然我在后面，但是我先输出了");
      //2)让对话框可见   响应式数据开发 ，操作都是数据
      this.editFormVisible=true;

    },
    //修改表单提交
    editSubmit(formName) {
      //表单验证 三步走  1) 定义规则  2)绑定规则  3)表单的validate方法来验证
      //1)表单 验证  表单.validate( callback(回调函数))
      //表单.validate( function callback(valid){ //处理验证的结果})
      //表单.validate( (valid)=>{})
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //2)验证通过，发送请求到后台 完成数据保存
          //发送axios请求  完成数据的接收
          //调用自己封装的请求实例
          let strData=this.qs.stringify(this.editForm);

          this.$request({
            method:'get',
            url: '/updateUsers',
            params:this.editForm
          },res=>{
            //刷新
            this.getUserList();
            this.$message({
              message: '保存成功',
              type: 'success',
              duration:0,
              showClose:true,
              offset:400
            });
          },error=>{
            //提示信息框
            console.log(error);
          },8100)

          //3)关闭窗口
          this.editFormVisible=false;
        } else {
          //2)验证不通过
          console.log('error submit!!');
          return false;//意味着表单不提交
        }
      });

    }
  }
}
</script>

<style scoped>
th{
  width: 20%;
  border: 1px;
}
td{
  width: 20%;
  border: 1px;
}
::v-deep .el-table,
::v-deep .el-table__expanded-cell {
  background-color: transparent !important;
  border: 1px;

}
/* 表格内背景颜色 */
::v-deep .el-table th,
::v-deep .el-table tr,
::v-deep .el-table td {
  background-color: transparent !important;
  text-align: center;
}
</style>